package com.cjf.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cjf.comon.CustomException;
import com.cjf.entity.Category;
import com.cjf.entity.Dish;
import com.cjf.entity.Setmeal;
import com.cjf.mapper.CategoryMapper;
import com.cjf.service.CategoryService;
import com.cjf.service.DishService;
import com.cjf.service.SetmealService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService {

    @Autowired
    private DishService dishService;

    @Autowired
    private SetmealService setmealService;
    /***
     * 根据id删除分类，删除前进行判断分类有没有绑定菜品
     * @param id
     */
    @Override
    public void remove(Long id) {
        LambdaQueryWrapper<Dish> dishLambdaQueryWrapper = new LambdaQueryWrapper<>();
        //添加查询条件，根据分类id进行查询
        dishLambdaQueryWrapper.eq(Dish::getCategoryId,id);
        //查询关联菜品的数据条数
        int count1 = dishService.count(dishLambdaQueryWrapper);
        //查询当前分类是否关联菜品，如果已关联则抛出业务异常
        if(count1 > 0) {
            //count1>0 已关联菜品 抛出业务异常
            throw new CustomException("当前分类下已关联菜品，不能删除");
        }

        //查询当前分类是否关联套餐，如果已关联则抛出业务异常
        LambdaQueryWrapper<Setmeal> setmealLambdaQueryWrapper = new LambdaQueryWrapper<>();
        //添加查询条件，根据分类id进行查询
        setmealLambdaQueryWrapper.eq(Setmeal::getCategoryId,id);
        //查询关联套餐的数据条数
        int count2 = dishService.count(dishLambdaQueryWrapper);

        if(count2 > 0) {
            //count2>0 已关联套餐 抛出业务异常
            throw new CustomException("当前分类下已关联套餐，不能删除");
        }

        //无关联，正常删除
        super.removeById(id);
    }
}
